//
//  SuperviseArrageDetailVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/1/10.
//
// 【首页-检查监督】检查任务-待整改-整改详情

import Foundation
import UIKit

class SuperviseArrageDetailVC: SubLevelViewController {
    
    let taskV = SuperviseArrageDetailView()
    
    var id: Int64!
    
    var datas: [SpRwbgtzModal?] = []

    var param: RwZgTzParam?

    init(id: Int64!) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
        self.param = RwZgTzParam(id: id)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "整改详情"
        navigationController?.navBarStyle(.white)
        view.backgroundColor = .bg
        
        setupUI()
        
        reloadData()
        
    }
    
    func reloadData() {
        API.getJcjdRwzgxq(withParam: SpDetailParam(id: id)) { responseModel in
            DispatchQueue.main.async {
                self.datas = responseModel.models ?? []
                self.taskV.reload(withModals: self.datas)
            }
        }
    }
    
    @objc func submitTapped() {
        let unChecks = datas.filter({($0?.rwzt == "1" || $0?.rwzt == "3")})

        let zgjls = taskV.zgjls
        
        if zgjls.count != unChecks.count {
            var isMbNot = false
            for data in unChecks {
                isMbNot = zgjls.filter({ $0.rwxid == data?.id }).count == 0
                if isMbNot {
                    view.showToast(witMsg: "请完成「\(data?.rwmc ?? "检查任务")」")
                    return
                }
            }
            return
        }
        
        let nots = zgjls.filter({($0.tzsm == "" || $0.fjImgs?.count == 0)})
        if nots.count > 0 {
            view.showToast(witMsg: "整改通过项，请添加图片及附加说明")
            return
        }
        
        view.showToastActivity()
        
        if zgjls.count == 0 {
            didSubmint()
            return
        }
        
        var tzParam: [RwjlTzParam] = []
        
        for zg in zgjls {
            if zg.fjImgs?.count == 0 {
                tzParam.append(RwjlTzParam(item: zg))
                if tzParam.count == zgjls.count {
                    param?.zgjls = tzParam
                    didSubmint()
                }
            } else {
                // 上传图片
                var uploadindex = 0
                var imageUrlList: [FjdzParam] = []
                for img in zg.fjImgs! {
                    let path = FilesManager.shared.saveImage(img: img.resizedTo1MB() ?? img)
                    API.lzglUpload(withImage: path!) { responseModel in
                        if responseModel.model?.imgUrl != nil {
                            imageUrlList.append(FjdzParam(fjdz: responseModel.model!.imgUrl!))
                        }
                        uploadindex += 1
                        if zg.fjImgs!.count == uploadindex {
                            tzParam.append(RwjlTzParam(item: zg, images: imageUrlList))
                            if tzParam.count == zgjls.count {
                                self.param?.zgjls = tzParam
                                self.didSubmint()
                            }
                        }
                    }
                }
            }
        }
    }
    
    func didSubmint() {
        do {
            let data: Data = try JSONEncoder().encode(self.param)
            let string = String(data: data, encoding: String.Encoding.utf8)
            API.postJcjdRwzgtj(withParam: CommonJsonParam(jsonStr: string)) { responseModel in
                self.view.hideToastActivity()
                if responseModel.errorCode == .Success {
                    NotificationCenter.default.post(name: NotiSupervise, object: nil)
                    self.navigationController?.popViewController(animated: true)
                }
            }
        } catch {
            print("postJcjdKsjctj error", error)
        }
    }
    
    // MARK: - Setup
    
    func setupUI() {
        taskV.submitBtn.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
        view.addSubview(taskV)
        taskV.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.left.right.equalToSuperview()
        }
    }
}
